<template>
  <div class="electricity-chart" ref="container"></div>
</template>

<script setup>
import {ref, watch, nextTick} from "vue";
import useEcharts from "../../utils/useCharts";

// 使用 ECharts 工具
const {container, setOption, clear, resize} = useEcharts();

const props = defineProps({
  tableData: {
    type: Array,
    default: () => [],
  },
  activeIndex: {
    type: Number,
    default: 1,
  },
});

const echartData = ref({});
const yAxisRange = ref({min: 0, max: 0}); // 保存 Y 轴的动态范围

// 处理 ECharts 数据
const processEchartData = () => {
  if (!props.tableData || props.tableData.length === 0) {
    clear();
    return;
  }

  // 提取 X 轴数据（startDate）
  const timeNames = Array.from(
      new Set(props.tableData.map((item) => item.startDate))
  ).sort();

  // 按 `stairs` 分组
  const stairGroups = [1, 2, 3, 4, 5].map((stair) => ({
    name: `阶梯${stair}`,
    type: "line",
    data: timeNames.map((time) => {
      const record = props.tableData.find(
          (item) => item.startDate === time && item.stairs === stair.toString()
      );
      return record ? parseFloat(record.electricityPrice) : 0;
    }),
  }));

  // 计算 Y 轴范围
  const allPrices = stairGroups
      .flatMap((group) => group.data)
      .filter((value) => !isNaN(value));
  const minPrice = Math.min(...allPrices);
  const maxPrice = Math.max(...allPrices);

  yAxisRange.value = {min: minPrice, max: maxPrice};

  echartData.value = {
    timeNames,
    seriesData: stairGroups,
  };

  // 更新 ECharts 配置
  const options = generateOptions();
  setOption(options);
};

// 生成 ECharts 配置
const generateOptions = () => {
  return {
    tooltip: {
      trigger: "axis",
      backgroundColor: "#2f2f48",
      textStyle: {color: "#fff"},
    },
    grid: {
      left: "8%",
      right: "2%",
      bottom: "12%",
      top: "5%",
    },
    legend: {
      data: echartData.value.seriesData.map((series) => series.name),
      textStyle: {fontSize: 12, color: "#000000"},
    },
    xAxis: {
      type: "category",
      data: echartData.value.timeNames,
      axisLabel: {color: "#9292c1", fontSize: 12, margin: 10},
    },
    yAxis: {
      type: "value",
      min: yAxisRange.value.min,
      max: yAxisRange.value.max,
      axisLabel: {color: "#9292c1"},
      splitLine: {
        lineStyle: {color: "#9292c130", type: "dashed"},
      },
    },
    series: echartData.value.seriesData,
  };
};

// 监听数据变化
watch(
    () => props.tableData,
    () => processEchartData(),
    {immediate: true, deep: true}
);

watch(
    () => props.activeIndex,
    (newVal) => {
      if (newVal === 2) {
        nextTick(() => {
          resize();
          processEchartData();
        });
      } else {
        nextTick(() => {
          clear();
        });
      }
    }
);
</script>

<style lang="scss" scoped>
.electricity-chart {
  width: 100%;
  height: calc(100% - 44px);
  min-height: 300px;
}
</style>
